package com.woniuxy.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import com.woniuxy.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.woniuxy.util.JwtUtil.parseJWT;

/**
 * @Author: linKe
 * @Date: 2022/2/10 17:08
 * @FileName: LoginController
 * @version: 1.0
 * @Description: 测试一个token 生成工具
 */
@Slf4j
@RestController
public class LoginController {

    @Value("${jwt.key}")
    public String jwtKey;


    @RequestMapping("/login/getToken")
    public String login(){

        // 生成jwt 10秒过期
        String jwt = JwtUtil.createJWT("1234567", 10000, "admin");
        // 生成token
        System.out.println(jwt);
        // 解析jwt
        Claims claims = parseJWT("1234567", jwt);
        // 获取用户名信息
        Object username = claims.get("username");
        // 解析token
        log.info("用户名:{}",username);
//        HttpServletRequest httpServletRequest = new HttpServletRequest();
//        httpServletRequest.getRequestDispatcher()
        return null;
    }
    @RequestMapping("/login/auth")
    public String login(String name, String pass, HttpServletResponse response){

        // 生成jwt 10秒过期
        String jwt = JwtUtil.createJWT("1234567", 10000, "admin");
        // 生成token
        System.out.println(jwt);
        // 解析jwt
        Claims claims = parseJWT("1234567", jwt);
        // 获取用户名信息
        Object username = claims.get("username");
        // 解析token
        log.info("用户名:{}",username);
//        HttpServletRequest httpServletRequest = new HttpServletRequest();
//        httpServletRequest.getRequestDispatcher()
        return null;
    }


    private DecodedJWT getJwtByToken(String token, String key, Map<String,String> claims) throws Exception{
        Algorithm algorithm = Algorithm.HMAC256(key);
        Verification verifier= JWT.require(algorithm)
                .withIssuer("liujb");
        if(claims!=null){
            claims.forEach((mapKey,mapValue)->{
                verifier.withClaim(mapKey,mapValue);
            });}
        JWTVerifier ver= verifier.build();
        DecodedJWT jwt=ver.verify(token);
        return jwt;
    }
}
